//
//  WSAccountController.m
//  BaseProject
//
//  Created by karong on 2023/8/7.
//

#import "WSAccountController.h"
#import "WSSettingRequest.h"
#import "WSAccountCell.h"
#import <Firebase.h>
#import <FirebaseAuth/FirebaseAuth.h>
#import <GoogleSignIn/GoogleSignIn.h>
#import <Firebase.h>
#import <FirebaseAuth/FirebaseAuth.h>
#import <AuthenticationServices/AuthenticationServices.h>

@interface WSAccountController () <UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding>

@property (weak, nonatomic) IBOutlet UICollectionView *listView;
@property (nonatomic, strong) NSMutableArray * dataArray;
@property (strong, nonatomic) NSString *appleNonce;
@end

@implementation WSAccountController

- (void)viewDidLoad {
    [super viewDidLoad];
    appConfig.startConfig.google_login = 1;
    [self setData];
}

- (void)setData {
    self.dataArray = [NSMutableArray new];
    WSBind * bind = [WSBind new];
    bind.leftStr = @"ID";
    bind.rightStr = WSSF(@"%ld", appUserCenter.id);
    bind.isBind = YES;
    [self.dataArray addObject:bind];
    if (@available(iOS 13.0, *)) {
        WSBind * google_bind = [WSBind new];
        google_bind.leftStr = APPLocalized(@"AppleId賬號");
        google_bind.rightStr = APPLocalized(@"已綁定");
        google_bind.type = @"apple";
        [self.dataArray addObject:google_bind];
    }
    if (appConfig.startConfig.google_login == 1) {
        WSBind * google_bind = [WSBind new];
        google_bind.leftStr = APPLocalized(@"Google賬號");
        google_bind.rightStr = APPLocalized(@"已綁定");
        google_bind.type = @"google.com";
        [self.dataArray addObject:google_bind];
    }
    [self.listView reloadData];
}

- (void)bindcharonTV_Request {
    WeakSelf
    [WSSettingRequest bindGoogleWithSuccess:^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakSelf setData];
        });
    } failed:^(NSURLResponse * _Nonnull response, NSError * _Nonnull error, id  _Nonnull responseObject) {
        
    }];
}

- (void)unbindcharonTV_Request:(WSBind *)bind {
    WeakSelf
    [WSSettingRequest unbindGoogleWithType:bind.type success:^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakSelf setData];
        });
    } failed:^(NSURLResponse * _Nonnull response, NSError * _Nonnull error, id  _Nonnull responseObject) {
        
    }];
}

- (void)bindGoogle {
    [WSToast loadingFull];
    [[GIDSignIn sharedInstance] signOut];
    GIDConfiguration *config = [[GIDConfiguration alloc] initWithClientID:[FIRApp defaultApp].options.clientID];
    [GIDSignIn.sharedInstance setConfiguration:config];
    [GIDSignIn.sharedInstance signInWithPresentingViewController:self completion:^(GIDSignInResult * _Nullable signInResult, NSError * _Nullable error) {
        //error.code != -5 用戶退出
        if(error) {
            [WSToast dismiss];
            if(!signInResult.user && !signInResult.user.profile && error.code != -5) {
                [WSToast simple:WSSF(@"Login failed\n%@", error.localizedDescription)];
            };
        }
        else {
            [signInResult.user refreshTokensIfNeededWithCompletion:^(GIDGoogleUser * _Nullable user,
                                                                                   NSError * _Nullable error) {
                              if (error) {
                                  NSLog(@"%@", error.localizedDescription);
                              } else {
                                  if (user == nil) {
                                      NSLog(@"signInResult.user is nil");
                                  } else {
                                      NSLog(@"user.userID:%@", user.userID);
                                      NSLog(@"user.idToken.tokenString:%@", user.idToken.tokenString);
                                  }
                              }
                          }];
            FIRAuthCredential *credential = [FIRGoogleAuthProvider credentialWithIDToken:signInResult.user.idToken accessToken:signInResult.user.accessToken];
            [self signInFirebaseWithCredential:credential accountType:0];
        }
    }];
}

- (void)bindApple {
    if (@available(iOS 13.0, *)) {
        self.appleNonce = [WSTools randomNonce:32];
        ASAuthorizationAppleIDProvider *appleIDProvider = [[ASAuthorizationAppleIDProvider alloc]init];
        ASAuthorizationAppleIDRequest *request = [appleIDProvider createRequest];
        request.requestedScopes = @[ASAuthorizationScopeFullName,ASAuthorizationScopeEmail];
        request.nonce = [WSTools stringBySha256HashingString:self.appleNonce];
        ASAuthorizationController *auth = [[ASAuthorizationController alloc]initWithAuthorizationRequests:@[request]];
        auth.delegate = self;
        auth.presentationContextProvider = self;
        [auth performRequests];
    }
}

- (void)signInFirebaseWithCredential:(FIRAuthCredential *)credential accountType:(NSInteger)accountType {
    [[FIRAuth auth] signInWithCredential:credential completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) {
        if (error || !authResult.user) {
            [WSToast simple:error.localizedDescription];
        }
        else {
            NSString *avator;
            if (authResult.user.photoURL) {
                avator = authResult.user.photoURL.absoluteString;
            }
            FIRUser *user = authResult.user;
            [user getIDTokenWithCompletion:^(NSString * _Nullable token, NSError * _Nullable error) {
                appUserCenter.qtoken = token;
                [self bindcharonTV_Request];
            }];
            
        }
    }];
}
#pragma mark UICollectionViewDelegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    WSAccountCell * cell;
    if (indexPath.row == 0) {
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"WSAccountCell" forIndexPath:indexPath];
        [cell setDataWithObject:self.dataArray[indexPath.row]];
    }
    else {
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"WSAccountBindCell" forIndexPath:indexPath];
        [cell setDataWithBindObject:self.dataArray[indexPath.row]];
    }
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGSize size = CGSizeZero;
    size.width = WSScreenWidth;
    size.height = 54;
    return size;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row > 0) {
        WSBind * bind = self.dataArray[indexPath.row];
        if (bind.isBind) {
            UIViewController * target = [[CTMediator sharedInstance]ct_showcharonTV_AlterWithTitle:WSSF(@"是否解除%@綁定", bind.leftStr) content:WSSF(@"解除綁定後將無法使用該%@進行登錄", bind.leftStr) confirm:@"確認" confirmHandle:^{
                [self unbindcharonTV_Request:bind];
            } cancel:@""];
            target.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
            target.modalPresentationStyle = UIModalPresentationCustom;
            [self presentViewController:target animated:YES completion:nil];
        }
        else if ([bind.type isEqualToString:@"apple"]) {
            [self bindApple];
        }
        else {
            [self bindGoogle];
        }
    }
}
@end
